<template>
  <div
    class="design-canvas"
    :style="canvasStyle"
    @click="handleCanvasClick"
    @drop="handleDrop"
    @dragover.prevent
    @dragenter.prevent
  >
    <!-- 画布网格背景 -->
    <div class="canvas-grid" v-if="showGrid"></div>

    <!-- 画布标尺 -->
    <div class="canvas-ruler-x" v-if="showRuler">
      <div
        v-for="i in rulerMarksX"
        :key="`x-${i}`"
        class="ruler-mark"
        :style="{ left: `${i * 10}px` }"
      >
        {{ i * 10 }}
      </div>
    </div>
    <div class="canvas-ruler-y" v-if="showRuler">
      <div
        v-for="i in rulerMarksY"
        :key="`y-${i}`"
        class="ruler-mark"
        :style="{ top: `${i * 10}px` }"
      >
        {{ i * 10 }}
      </div>
    </div>

    <!-- 组件渲染区域 -->
    <div class="canvas-content" ref="canvasRef">
      <ComponentRenderer
        v-for="component in components"
        :key="component.id"
        :component="component"
        @mousedown="handleComponentMouseDown($event, component)"
      />

      <!-- 空状态提示 -->
      <div v-if="components.length === 0" class="empty-state">
        <el-icon class="empty-icon"><Box /></el-icon>
        <p>拖拽左侧组件到此处开始设计</p>
        <p class="empty-tip">或者点击左侧组件直接添加</p>
      </div>
    </div>

    <!-- 拖拽预览 -->
    <div
      v-if="dragPreview.show"
      class="drag-preview"
      :style="dragPreviewStyle"
    >
      {{ dragPreview.componentType }}
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useEditorStore } from '@/stores/editor'
import ComponentRenderer from './ComponentRenderer.vue'
import { Box } from '@element-plus/icons-vue'

const editorStore = useEditorStore()

// 画布引用
const canvasRef = ref(null)

// 显示配置
const showGrid = ref(true)
const showRuler = ref(false)

// 拖拽预览
const dragPreview = ref({
  show: false,
  x: 0,
  y: 0,
  componentType: ''
})

// 拖拽状态
const isDragging = ref(false)
const dragOffset = ref({ x: 0, y: 0 })
const dragComponent = ref(null)

// 计算属性
const components = computed(() => editorStore.components)

const canvasStyle = computed(() => ({
  ...editorStore.canvasConfig,
  position: 'relative',
  minHeight: '100vh',
  overflow: 'hidden'
}))

// 标尺刻度
const rulerMarksX = computed(() => {
  return Array.from({ length: 50 }, (_, i) => i + 1)
})

const rulerMarksY = computed(() => {
  return Array.from({ length: 50 }, (_, i) => i + 1)
})

// 拖拽预览样式
const dragPreviewStyle = computed(() => ({
  position: 'fixed',
  left: `${dragPreview.value.x}px`,
  top: `${dragPreview.value.y}px`,
  pointerEvents: 'none',
  zIndex: 1000,
  background: 'rgba(64, 158, 255, 0.8)',
  color: 'white',
  padding: '4px 8px',
  borderRadius: '4px',
  fontSize: '12px'
}))

// 处理画布点击
const handleCanvasClick = (event) => {
  // 如果点击的是画布本身，清除选中
  if (event.target.classList.contains('design-canvas') ||
      event.target.classList.contains('canvas-content')) {
    editorStore.clearSelection()
  }
}

// 处理拖拽放置
const handleDrop = (event) => {
  event.preventDefault()

  try {
    const data = JSON.parse(event.dataTransfer.getData('application/json'))

    if (data.type === 'component') {
      const rect = canvasRef.value.getBoundingClientRect()
      const position = {
        x: event.clientX - rect.left,
        y: event.clientY - rect.top
      }

      editorStore.addComponent(data.componentType, position)
    }
  } catch (error) {
    console.error('拖拽数据解析失败:', error)
  }

  dragPreview.value.show = false
}

// 处理组件鼠标按下（开始拖拽）
const handleComponentMouseDown = (event, component) => {
  if (event.button !== 0) return // 只处理左键

  event.preventDefault()
  event.stopPropagation()

  // 选中组件
  editorStore.selectComponent(component.id)

  // 开始拖拽
  isDragging.value = true
  dragComponent.value = component

  const rect = canvasRef.value.getBoundingClientRect()
  dragOffset.value = {
    x: event.clientX - rect.left - component.position.x,
    y: event.clientY - rect.top - component.position.y
  }

  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
}

// 处理鼠标移动（拖拽中）
const handleMouseMove = (event) => {
  if (!isDragging.value || !dragComponent.value) return

  const rect = canvasRef.value.getBoundingClientRect()
  const newPosition = {
    x: Math.max(0, event.clientX - rect.left - dragOffset.value.x),
    y: Math.max(0, event.clientY - rect.top - dragOffset.value.y)
  }

  editorStore.updateComponentPosition(dragComponent.value.id, newPosition)
}

// 处理鼠标抬起（结束拖拽）
const handleMouseUp = () => {
  isDragging.value = false
  dragComponent.value = null

  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)
}

// 键盘事件处理
const handleKeyDown = (event) => {
  // 删除选中组件
  if (event.key === 'Delete' && editorStore.selectedComponentId) {
    editorStore.removeComponent(editorStore.selectedComponentId)
  }

  // 复制组件
  if (event.ctrlKey && event.key === 'c' && editorStore.selectedComponent) {
    // 这里可以实现复制功能
    console.log('复制组件')
  }

  // Esc 取消选中
  if (event.key === 'Escape') {
    editorStore.clearSelection()
  }
}

onMounted(() => {
  document.addEventListener('keydown', handleKeyDown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyDown)
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)
})

// 暴露方法给父组件
defineExpose({
  toggleGrid: () => { showGrid.value = !showGrid.value },
  toggleRuler: () => { showRuler.value = !showRuler.value }
})
</script>

<style lang="scss" scoped>
.design-canvas {
  position: relative;
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  overflow: auto;
}

.canvas-grid {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image:
    linear-gradient(90deg, rgba(0,0,0,0.05) 1px, transparent 1px),
    linear-gradient(180deg, rgba(0,0,0,0.05) 1px, transparent 1px);
  background-size: 20px 20px;
  pointer-events: none;
  z-index: 1;
}

.canvas-ruler-x,
.canvas-ruler-y {
  position: absolute;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid #e4e7ed;
  z-index: 10;

  .ruler-mark {
    position: absolute;
    font-size: 10px;
    color: #666;
    user-select: none;
  }
}

.canvas-ruler-x {
  top: 0;
  left: 20px;
  right: 0;
  height: 20px;

  .ruler-mark {
    top: 2px;
    transform: translateX(-50%);
  }
}

.canvas-ruler-y {
  left: 0;
  top: 20px;
  bottom: 0;
  width: 20px;

  .ruler-mark {
    left: 2px;
    transform: translateY(-50%);
    writing-mode: vertical-lr;
  }
}

.canvas-content {
  position: relative;
  width: 100%;
  min-height: 100%;
  z-index: 2;
}

.empty-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #909399;
  user-select: none;
  pointer-events: none;

  .empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
    color: #c0c4cc;
  }

  p {
    margin: 8px 0;
    font-size: 14px;
  }

  .empty-tip {
    font-size: 12px;
    color: #c0c4cc;
  }
}

.drag-preview {
  position: fixed;
  pointer-events: none;
  user-select: none;
}

// 拖拽时的鼠标样式
.design-canvas {
  &.dragging {
    cursor: grabbing !important;

    * {
      cursor: grabbing !important;
    }
  }
}
</style>
